<template>
  <div class="amap-wrapper">
    <a-map :options="{ zoom: 15 }" @AMapAction="initLoad"> </a-map>
  </div>
</template>
<script>
import aMap from './aMap'
export default {
  name: 'App',
  components: {
    aMap
  },
  data() {
    return {
      map: null
    }
  },
  created() {},
  mounted() {},
  methods: {
    initLoad(AMap, map) {
      this.map = map
      // console.log('触发地图资源加载完成事件')
      AMap.plugin(['AMap.Driving'], () => {
        // 加载驾车服务插件
        var drivingOptions = {
          // 驾车策略，包括 LEAST_TIME，LEAST_FEE, LEAST_DISTANCE,REAL_TRAFFIC
          policy: AMap.DrivingPolicy.LEAST_TIME
        }
        var driving = new AMap.Driving(drivingOptions)
        console.log(driving)
        // 根据起终点坐标规划驾车路线
        driving.search(
          new AMap.LngLat(119.019161, 25.478085),
          new AMap.LngLat(119.007662, 25.454202),
          (status, result) => {
            console.log(status, result)
            // result即是对应的驾车导航信息，相关数据结构文档请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
            if (status === 'complete') {
              if (result.routes && result.routes.length) {
                // 绘制第一条路线，也可以按需求绘制其它几条路线
                var route = result.routes[0]
                var path = []
                for (var i = 0, l = route.steps.length; i < l; i++) {
                  var step = route.steps[i]
                  for (var j = 0, n = step.path.length; j < n; j++) {
                    path.push(step.path[j])
                  }
                }
                var startMarker = new AMap.Marker({
                  position: path[0],
                  icon: '/static/img/start.png',
                  map: this.map
                })
                var endMarker = new AMap.Marker({
                  position: path[path.length - 1],
                  icon: '/static/img/end.png',
                  map: this.map
                })
                var routeLine = new AMap.Polyline({
                  path: path,
                  isOutline: true,
                  outlineColor: '#ffeeee',
                  borderWeight: 2,
                  strokeWeight: 5,
                  strokeOpacity: 0.9,
                  strokeColor: '#0091ff',
                  lineJoin: 'round'
                })
                // map.add(routeLine);
                this.map.add([startMarker, endMarker, routeLine])
                this.map.setFitView()
                console.log('绘制驾车路线完成')
              }
            } else {
              console.log('获取驾车数据失败：' + result)
            }
          }
        )
      })
    }
  }
}
</script>

<style scoped>
.amap-wrapper {
  height: 100%;
  width: 100%;
  margin: 0;
}
</style>
